package com.retoc.oawx.config.shiro;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.retoc.oawx.domain.User;
import com.retoc.oawx.service.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Set;

@Component
public class OAuth2Realm extends AuthorizingRealm {

    @Autowired
    private JWTUtil jwtUtil;

    @Autowired
    private UserService userService;

    @Override
    public boolean supports(AuthenticationToken token){
        return token instanceof OAuth2Token;
    }

    //授权，验证权限
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection collection) {
        User user = (User) collection.getPrimaryPrincipal();
        int userId = user.getId();
        Set<String> permissions = userService.searchUserPermissions(userId);
        SimpleAuthorizationInfo info=new SimpleAuthorizationInfo();
        info.setStringPermissions(permissions);
        return info;
    }

    //认证登陆
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {

        String accessToken = (String) token.getPrincipal();
        int userId=jwtUtil.getUserId(accessToken);
//        QueryWrapper<User> qw = new QueryWrapper<>();
//        qw.eq("id",userId);
//        User user = userService.getOne(qw);
        User user = userService.searchById(userId);
        System.out.println(user);
        if (user == null) {
            throw new LockedAccountException("账号已被锁定，请联系管理员");
        }
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user,accessToken,getName());
        return info;
    }
}
